package oss.controller;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import oss.git.GitAsOssUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;


@Controller
public class UploadController {

    @RequestMapping("/")
    @ResponseBody
    public ResponseEntity<String> upload(HttpServletRequest request) throws IllegalStateException, IOException {
        String url = null;
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> fileNames = multiRequest.getFileNames();
            while (fileNames.hasNext()) {
                MultipartFile file = multiRequest.getFile(fileNames.next().toString());
                if (file != null) {
                    url = GitAsOssUtil.add(file.getOriginalFilename(),file.getInputStream());
                }
            }
        }

        return ResponseEntity.ok(url);
    }


}
